<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 树形组件 -->
        <!-- default-expand-all是否展开子组件 -->
        <el-tree
          :data="list"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- {data}data是固定的吗? 是固定的 解构赋值的写法 -->
          <!-- #default="scope" scoped不是固定的 类似于函数的形参 -->
          <!-- 用组件都是已经写好了一般 容许我们传入参数 也给我们抛出了现成的数据 -->
          <template #default="{ data }">
            <!-- 自定义的模板 -->
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="addDepart(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="editDepart(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delDepart(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                      <!-- <template>
                        <el-button type="text" @click="delDepart" />
                      </template> -->
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>

      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="30%"
      center
      @close="closeDialog"
      @open="openDialog"
    >
      <template #default>
        <el-form ref="addForm" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
              <!-- label:下拉框中文显示 -->
              <!-- value:选中的那一项的value值会自动绑定到form.manager 提交给后端 -->
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDepartmentList, fetchManagerList, fetchAddDepartAPI, fetchDetail, fetchUpdateDepart, fetchDelDepart } from '@/api/department'
import transTree from '@/utils/transTree'

export default {
  name: 'Department',
  data() {
    const validatePass = (rule, value, callback) => {
      let codeList = []
      if (this.form.id) {
        codeList = this.childList.filter(code => code !== this.cacheCode)
      } else {
        codeList = this.childList
      }
      if (codeList.includes(value)) {
        callback('重复请重新输入')
      } else {
        callback()
      }
    }
    return {
      // 依赖一份树形数据
      list: [],
      // 当前编辑的code码
      defaultProps: {
        label: 'name'
      },
      cacheCode: null, // 编辑状态的code码
      dialogVisible: false, // 弹框显示隐藏
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''// 当前的父id
      },
      rules: {
        code: [
          { required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人必填', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300个字符', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍必填', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      managerList: [], // 部门负责人列表,
      childList: [] // 子级数组

    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList() {
      const res = await fetchDepartmentList()
      res.depts.forEach(item => {
        if (item.code) {
          this.childList.push(item.code)
        }
      })
      //  树形数据处理
      this.list = transTree(res.depts)
    },
    // 添加子部门时触发
    addDepart(id) {
      this.form.pid = id
      this.dialogVisible = true
    },
    // 弹框关闭函数
    closeDialog() {
      // 弹框关闭重置表单
      this.$refs.addForm.resetFields()
      this.dialogVisible = false
    },
    // 弹框关闭触发
    async openDialog() {
      const res = await fetchManagerList()
      this.managerList = res
    },
    // 兜底校验
    // 新增
    confirm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          // 用有无id判断调用编辑和新增的接口
          if (this.form.id) {
            // 更新接口
            await fetchUpdateDepart(this.form)
          } else {
            await fetchAddDepartAPI(this.form)
          }

          // 提示字段
          this.$message.success(`${this.form.id ? '编辑' : '新增'}部门成功`)
          // 关闭弹框
          this.dialogVisible = false
          // 重新渲染页面
          this.getList()
          // 重置表单
          this.$refs.addForm.resetFields()
          this.restForm()
        }
      }
      )
    },
    // 因为id删不掉一直是由值就会一直编辑
    restForm() {
      this.form = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''// 当前的父id
      }
    },
    // 删除
    delDepart(id) {
      this.$confirm('确认删除此部门吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 删除逻辑
        await fetchDelDepart(id)
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {

      })
    },
    // 编辑
    async editDepart(id) {
      // 打开弹窗
      this.dialogVisible = true
      const res = await fetchDetail(id)
      // 数据回填到form上面
      this.form = res
      // 暂存当前的code码
      this.cacheCode = res.code
    }

  }
}

</script>

<style>

</style>
